package com.naizhuai.network.Cookie.persistent;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;

/**
 * @author：lichenxi
 * @date 2018/1/11 16
 * email：525603977@qq.com
 * Fighting
 */
public class SpCookiePersistor implements CookiePersistor {
   private SharedPreferences  sharedPreferences;

    public SpCookiePersistor(SharedPreferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }


    public  SpCookiePersistor(Context context){
        this(context.getSharedPreferences("CookiePersistence", Context.MODE_PRIVATE));
    }

    @Override
    public List<Cookie> LoadAll() {
         List<Cookie> cookies=new ArrayList<>(sharedPreferences.getAll().size());
         for (Map.Entry<String,?> value : sharedPreferences.getAll().entrySet()){
              Cookie cookie=new SerializableCookie().decode((String) value.getValue());
              if (cookie!=null){
                cookies.add(cookie);
             }
        }
        return cookies;
    }

    @Override
    public void SaveAll(Collection<Cookie> cookies) {
        SharedPreferences.Editor editor=sharedPreferences.edit();
        for (Cookie cookie: cookies) {
            //把Cookie流话 保存在磁盘中
            editor.putString(createCookieKey(cookie),new SerializableCookie().encode(cookie));
        }
        editor.commit();
    }

    @Override
    public void RemoveAll(Collection<Cookie> cookies) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        for (Cookie cookie : cookies) {
            editor.remove(createCookieKey(cookie));
        }
        editor.commit();
    }

    @Override
    public void clear() {
        sharedPreferences.edit().clear().commit();
    }
    private String createCookieKey(Cookie cookie) {
        return isHttps(cookie) + "://" + cookie.domain() + cookie.path() + "|" + cookie.name();
    }
    private String isHttps(Cookie cookie){
       if (cookie.secure()){
           return "https";
        } else{
           return  "http";
       }
    }
}
